package com.leyou.upload.service;

import com.github.tobato.fastdfs.domain.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.ImageReader;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Arrays;
import java.util.List;

@Service
public class UploadService {


    @Autowired
    private FastFileStorageClient storageClient;

    private static final Logger logger = LoggerFactory.getLogger(UploadService.class);

    // 支持的文件类型
    private static final List<String> suffixes = Arrays.asList("image/png", "image/jpeg");

    public String uploadImage(MultipartFile file) {
        try {
            //允许上传的大小

            //限制上传的类型，jpg,png
            //8+3,jpg,jpe,jpeg,avi,png,mp4,doc,exe

            String contentType = file.getContentType();

            if (!suffixes.contains(contentType)){
                logger.info("文件类型不匹配：{}",contentType);
            }

            //校验内容
            BufferedImage read = ImageIO.read(file.getInputStream());

            if (read==null){
                logger.info("文件内容不匹配");
            }


            //做文件的上传，IO

            String filename = file.getOriginalFilename();


            String ext = StringUtils.substringAfterLast(filename, ".");


            StorePath storePath = storageClient.uploadFile(file.getInputStream(), file.getSize(), ext, null);

            String fullPath = storePath.getFullPath();
            return "http://image.leyou.com/"+fullPath;
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;
    }
}
